#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // QTimer 是 Qt 中的定时器类, 使用 QTimer 可以实现一些重复定时任务

    // 创建定时器对象
    QTimer *timer = new QTimer(this);

    // 从堆区创建计时器变量, 后续其他函数就可以正常的实现计时器计数的功能
    int *p = (int *)malloc(sizeof(int));

    // Start 按钮的点击事件
    connect(ui->push_button_01, &QPushButton::clicked, this, [=](){
        // 计时器归零
        *p = 0;

        // 启动定时器
        timer->start(10);
    });

    // End 按钮的点击事件
    connect(ui->push_button_02, &QPushButton::clicked, this, [=]() {
        timer->stop();
    });

    // 定时任务
    connect(timer, &QTimer::timeout, this, [=]() {
        int minute = 0;
        int second = 0;
        int milli_second = 0;

        milli_second = *p;
        second = milli_second / 100;
        milli_second %= 100;
        minute = second / 60;
        second %= 60;

        std::string counter_text = "";
        if (minute < 10) {
            counter_text += std::string("0");
        }
        counter_text += std::to_string(minute);
        counter_text += std::string(":");
        if (second < 10) {
            counter_text += std::string("0");
        }
        counter_text += std::to_string(second);
        counter_text += std::string(":");
        if (milli_second < 10) {
            counter_text += std::string("0");
        }
        counter_text += std::to_string(milli_second);

        ui->time_label_01->setText(QString::fromStdString(counter_text));

        (*p)++;
    });
}

Widget::~Widget()
{
    delete ui;
}

